﻿Imports System.Windows.Controls.Primitives
Imports System.Windows.Media.Media3D

Public Class MoveThumb
    Inherits Thumb

    Public Sub New()
        AddHandler Me.DragDelta, AddressOf Me.MoveThumb_DragDelta
    End Sub

    Private Sub MoveThumb_DragDelta(ByVal sender As Object, ByVal e As DragDeltaEventArgs)

        'Récupérer l'élément enfant du canvas
        Dim CanvasChild As UIElement = FindCanvasChild(Me)
        'Dim designerItem As Control = DirectCast(Me.DataContext, Control)

        If (CanvasChild IsNot Nothing) Then

            Dim left As Double = Canvas.GetLeft(CanvasChild)
            Dim top As Double = Canvas.GetTop(CanvasChild)

            Canvas.SetLeft(CanvasChild, left + e.HorizontalChange)
            Canvas.SetTop(CanvasChild, top + e.VerticalChange)
        End If
    End Sub

    ''' <summary>
    ''' Parcourt l'arbre visuel à partir de l'élément depObj en recherchant un UIElement
    ''' enfant direct d'un Canvas. Si un tel élément n'est pas trouvé, la fonction renvoie Noting.
    ''' </summary>
    ''' <param name="depObj">
    ''' Un DependencyObject à partir duquelle la recherche débute.
    ''' </param>
    Public Function FindCanvasChild(ByVal depObj As DependencyObject) As UIElement

        While depObj IsNot Nothing

            'Dim elem As UIElement = TryCast(depObj, UIElement)

            ' VisualTreeHelper works with objects of type Visual or Visual3D.
            ' If the current object is not derived from Visual or Visual3D,
            ' then use the LogicalTreeHelper to find the parent element.
            If (TypeOf depObj Is Visual) Or (TypeOf depObj Is Visual3D) Then
                If TypeOf (VisualTreeHelper.GetParent(depObj)) Is Canvas Then
                    Exit While
                Else
                    depObj = VisualTreeHelper.GetParent(depObj)
                End If
            Else
                If TypeOf (LogicalTreeHelper.GetParent(depObj)) Is Canvas Then
                    Exit While
                Else
                    depObj = LogicalTreeHelper.GetParent(depObj)
                End If
            End If

        End While

        Return TryCast(depObj, UIElement)

    End Function

End Class